package com.example.shop.sys.dept.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.shop.base.BaseController;
import com.example.shop.base.Result;
import com.example.shop.domain.sys.SysDept;
import com.example.shop.sys.dept.service.SysDeptService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门机构控制器
 *
 * @author haocj
 */
@RestController
@RequestMapping(value = "/sys/sysDept")
public class SysDeptController extends BaseController {

    @Autowired
    private SysDeptService sysDeptService;

    @ModelAttribute
    public SysDept get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            return sysDeptService.get(id);
        } else {
            return new SysDept();
        }
    }


    @RequestMapping(value = "/info")
    public List<SysDept> list(SysDept sysDept) {
        return sysDeptService.findList(sysDept);
    }


    @RequestMapping(value = "/getById")
    public SysDept getById(SysDept sysDept) {
        SysDept dept = sysDeptService.get(sysDept);
        SysDept sd = sysDeptService.get(sysDept.getParentId());
        if (sd != null) {
            dept.setParentName(sd.getDeptName());
        }
        return dept;
    }

    /**
     * 新增 修改
     *
     * @param sysDept
     * @return
     */
    @RequestMapping(value = "/save")
    public Result save(SysDept sysDept) {
        sysDeptService.save(sysDept);
        return Result.success("保存成功");
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Result delete(@RequestParam("id") String[] ids) {
        sysDeptService.delete(ids);
        return Result.success();
    }

    /**
     * 部门数据
     *
     * @return
     */
    @RequestMapping(value = "/zTreeNodes")
    public Result<JSONArray> getZTreeNodes() {

        JSONArray array = new JSONArray();
        JSONObject object = null;
        List<SysDept> list = sysDeptService.findList(new SysDept());
        for (SysDept dept : list) {
            object = new JSONObject();
            object.put("id", dept.getId());
            object.put("pId", dept.getParentId());
            object.put("name", dept.getDeptName());
            array.add(object);
        }
        return new Result<>(1, "success", array);
    }
}
